import os
from flask import request

from vulcanus.log.log import LOGGER
from vulcanus.restful.response import BaseResponse
from vulcanus.restful.resp.state import (
    DATABASE_INSERT_ERROR,
    PARAM_ERROR,
    SUCCEED,
)

from zeus.operation_service.app.core.asset import ASSET_PATH
from zeus.operation_service.app.core.asset.tools.file_response import build_file_response
from zeus.operation_service.app.core.asset.tools.zip_asset import zip_asset
from zeus.operation_service.app.proxy.asset import AssetProxy
from zeus.operation_service.app.core.asset.asset_exception import AssetError
from zeus.operation_service.app.core.asset.asset_util.asset_decompress import validate_asset
from zeus.operation_service.app.core.asset.asset_util.asset_save import save_asset


class AssetManageAPI(BaseResponse):
    @BaseResponse.handle(proxy=AssetProxy, token=False)
    def get(self, callback: AssetProxy, **params):
        status_code, result = callback.get_assets(params)
        return self.response(code=status_code, data=result)

    @BaseResponse.handle(token=False)
    def post(self, **params):
        file = request.files.get('file')
        if file is None or not file.filename:
            return self.response(code=PARAM_ERROR)
        try:
            LOGGER.info(f"begin upload asset:{file.filename}")
            result = validate_asset(file)
            save_asset(result)
            return self.response(code=SUCCEED)
        except AssetError as asset_exception:
            response = dict(code=asset_exception.error_code, message=asset_exception.error_info, label=asset_exception.error_info)
            return response
        except Exception as e:
            return self.response(code=DATABASE_INSERT_ERROR)

    @BaseResponse.handle(proxy=AssetProxy, token=False)
    def delete(self, callback: AssetProxy, **params):
        status_code, result = callback.batch_delete_asset(params['data'])
        return self.response(code=status_code, data=result)


class AssetDownloadAPI(BaseResponse):
    @BaseResponse.handle(token=False)
    def post(self, **params):
        asset_id = params['asset_id']
        asset = AssetProxy().get_asset_by_asset_id(asset_id)
        asset_dir = asset.asset_dir
        asset_dir_path = os.path.join(ASSET_PATH, asset_dir)
        LOGGER.info(f"get asset:{asset_dir}")
        if os.path.isfile(os.path.join(ASSET_PATH, 'asset_download', f"{asset_dir}.zip")):
            LOGGER.info(f"download {os.path.join(ASSET_PATH, 'asset_download', asset_dir)}")
            return build_file_response(os.path.join(ASSET_PATH, 'asset_download', f"{asset_dir}.zip"))
        if not os.path.isdir(os.path.join(ASSET_PATH, 'asset_download')):
            os.mkdir(os.path.join(ASSET_PATH, 'asset_download'))
        zip_asset(asset_dir_path, asset.item_dir, asset.scene_dir)
        LOGGER.info(f"download {os.path.join(ASSET_PATH, 'asset_download', asset_dir)}")
        return build_file_response(os.path.join(ASSET_PATH, 'asset_download', f"{asset_dir}.zip"))